<template>
  <div>
    <home-header></home-header>
    <home-swiper :list="swiperList"></home-swiper>
    <icons :list="iconList"></icons>
    <home-recommend :list="recommendList"></home-recommend>
    <weekend :list="weekendList"></weekend>
  </div>
</template>

<script>
import HomeHeader from './components/header'
import HomeSwiper from './components/Swiper'
import Icons from './components/Icons'
import HomeRecommend from './components/recommend'
import Weekend from './components/weekend'
import axios from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    Icons,
    HomeRecommend,
    Weekend
  },
  data () {
    return {
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: [],
      lastCity: ''
    }
  },
  computed: {
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.city)
        .then(this.getInfoSuss)
    },
    getInfoSuss (res) {
      var result = res.data
      if (result.ret && result.data) {
        const data = result.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    this.getHomeInfo()
    this.lastCity = this.city // 刚挂载时初始化上次城市等于这次城市
  },
  activated () { // 当使用keepalive时才会出现这个生命周期函数
    // 在页面重新显示的时候调用,现在这个钩子在home页面所以home页面第一次显示和以后再显示的时候调用
    if (this.lastCity !== this.city) { // 当上次城市不等于这次城市时重新发送ajax请求
      this.lastCity = this.city // 如果不重新设置上次城市,上次城市就会在页面第一次挂载的时候固定为初始值,
      // 如果这样即使后面连续选了两次相同的城市,依然会重新发送ajax请求
      this.getHomeInfo()
    }
  }
}
</script>

<style>
</style>
